//
//  FjpgViewController.m
//  OutesIOS
//
//  Created by norman on 2018/11/18.
//  Copyright © 2018 norman. All rights reserved.
//

#import "FjpgViewController.h"
#import "UITapView.h"
#import "HttpTool.h"
#import "ProductDetailViewController.h"
#import "ProductListTableViewCell.h"

@interface FjpgViewController () {
}

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSArray *dataSource;
@property (nonatomic,strong) NSArray *selectionData0;
@property (nonatomic,strong) NSArray *selectionData1;
@property (nonatomic,strong) NSArray *selectionData2;

@property (nonatomic,strong) UILabel *lbSeries;
@property (nonatomic,strong) UILabel *lbStruct;
@property (nonatomic,strong) UILabel *lbSetup;

@property (nonatomic,strong) UIImageView *ivDirector1;
@property (nonatomic,strong) UIImageView *ivDirector2;
@property (nonatomic,strong) UIImageView *ivDirector3;

@property (nonatomic,strong) NSArray *selectDevices;

@end

@implementation FjpgViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"风机盘管";
    [self initData];
    [self setupViews];
}

/**
 *  初始化数据
 */
- (void)initData {
    self.dataSource = [NSMutableArray new];
    self.selectDevices = [NSMutableArray new];
}

#pragma mark - 初始化视图
- (void)setupViews{
    if (self.machineSelectedBlock != nil) {
        //自定义完成选择按钮
        UIBarButtonItem *saveBtn = [[UIBarButtonItem alloc] initWithTitle:@"完成选择" style:UIBarButtonItemStyleDone target:self action:@selector(onSave)];
        self.navigationItem.rightBarButtonItem = saveBtn;
        
        //自定义返回按钮
        UIBarButtonItem *returnBtn = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(onReturn)];
        self.navigationItem.leftBarButtonItem = returnBtn;
    }
    
    [self setupFilterView];
    
    self.tableView = [[UITableView alloc] initWithFrame:[UIView frameWithOutNav] style:UITableViewStylePlain];
    [self.tableView registerClass:[ProductListTableViewCell class] forCellReuseIdentifier:@"list"];
    self.tableView.y += 50;
    self.tableView.height -= 50;
    self.tableView.backgroundColor = CM_TABLE_BG_COLOR;
    [self.tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [self.tableView.mj_header beginRefreshing];
}

- (void)loadData {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if (![self.lbSeries.text containsString:@"产品系列"]) {
        [param setValue:self.lbSeries.text forKey:@"series"];
    } else {
         [param setValue:@"" forKey:@"series"];
    }
    if (![self.lbStruct.text containsString:@"结构型式"]) {
        [param setValue:self.lbStruct.text forKey:@"struct"];
    } else {
        [param setValue:@"" forKey:@"struct"];
    }
    if (![self.lbSetup.text containsString:@"安装型式"]) {
        [param setValue:self.lbSetup.text forKey:@"install"];
    } else {
        [param setValue:@"" forKey:@"install"];
    }
    [HttpTool get:HTTP_GET_EQUIP_FCU_QUERY params:param success:^(NSDictionary *responseObj) {
        [self.tableView.mj_header endRefreshing];
        self.dataSource = [responseObj objectForKey:@"equips"];
        self.selectionData0 = [responseObj objectForKey:@"allSeries"];
        self.selectionData1 = [responseObj objectForKey:@"allStruct"];
        self.selectionData2 = [responseObj objectForKey:@"allInstall"];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
    }];
   
//    [HttpClient getWithUrl:HTTP_GET_EQUIP_FCU_QUERY paramDic:param resultClass:[NSDictionary class] success:^(NSDictionary *obj) {
//        //下拉刷新
//        self.dataSource = [obj objectForKey:@"equips"];
//
//    } failure:^(NSError *error) {
//
//    }];
}

#pragma mark - 事件响应
- (void)onSave {
    if (self.selectedGuids == nil || self.selectedGuids.count == 0) {
        [Tools showMessageCenter:@"您还没有选择设备！"];
        return;
    }
    NSMutableArray *equips = [NSMutableArray new];
    for (NSString *guid in self.selectedGuids) {
        for (NSDictionary *item in self.dataSource) {
            if ([guid isEqualToString:[item objectForKey:@"Id"]]) {
                [equips addObject:item];
                break;
            }
        }
    }
    self.machineSelectedBlock(equips);
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onReturn {
    if (self.selectedGuids != nil && self.selectedGuids.count > 0) {
        NSMutableArray *equips = [NSMutableArray new];
        for (NSString *guid in self.selectedGuids) {
            for (NSDictionary *item in self.dataSource) {
                if ([guid isEqualToString:[item objectForKey:@"Id"]]) {
                    [equips addObject:item];
                    break;
                }
            }
        }
        self.machineSelectedBlock(equips);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setupFilterView {
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 50)];
    header.backgroundColor = [UIColor whiteColor];
    
    UITapView *view1 = [[UITapView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width/3, 50)];
    [view1 addTargetsBlock:^(id obj) {
        [self filterSelection:1];
    }];
    [header addSubview:view1];
    
    UIImageView *filter = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"filter"]];
    filter.x = 10;
    filter.centerY = view1.height/2;
    [view1 addSubview:filter];
    
    self.lbSeries = [UILabel labelSingleLineFontSize:kListTitleFontSize content:@"产品系列"];
    self.lbSeries.textColor = BSBlackTextColor;
    self.lbSeries.x = CGRectGetMaxX(filter.frame) + 2;
    self.lbSeries.centerY = view1.height/2;
    self.lbSeries.width = view1.width - self.lbSeries.x - 5;
    [view1 addSubview:self.lbSeries];
    
    UIView *line1 = [[UIView alloc]initWithFrame:CGRectMake(kScreen_Width/3, 5, 1, 40)];
    line1.backgroundColor = CM_TABLE_BG_COLOR;
    [header addSubview:line1];
    
    UITapView *view2 = [[UITapView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(line1.frame), 0, kScreen_Width/3, 50)];
    [view2 addTargetsBlock:^(id obj) {
        [self filterSelection:2];
    }];
    [header addSubview:view2];
    
    UIImageView *filter2 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"filter"]];
    filter2.x = 10;
    filter2.centerY = view2.height/2;
    [view2 addSubview:filter2];
    
    self.lbStruct = [UILabel labelSingleLineFontSize:kListTitleFontSize content:@"结构型式"];
    self.lbStruct.textColor = BSBlackTextColor;
    self.lbStruct.x = CGRectGetMaxX(filter.frame) + 2;
    self.lbStruct.centerY = view2.height/2;
    self.lbStruct.width = view2.width - self.lbStruct.x - 5;
    [view2 addSubview:self.lbStruct];
    
    UIView *line2 = [[UIView alloc]initWithFrame:CGRectMake(kScreen_Width*2/3, 5, 1, 40)];
    line2.backgroundColor = CM_TABLE_BG_COLOR;
    [header addSubview:line2];
    
    UITapView *view3 = [[UITapView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(line2.frame), 0, kScreen_Width/3, 50)];
    [view3 addTargetsBlock:^(id obj) {
        [self filterSelection:3];
    }];
    [header addSubview:view3];
    
    UIImageView *filter3 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"filter"]];
    filter3.x = 10;
    filter3.centerY = view3.height/2;
    [view3 addSubview:filter3];
    
    self.lbSetup = [UILabel labelSingleLineFontSize:kListTitleFontSize content:@"安装型式"];
    self.lbSetup.textColor = BSBlackTextColor;
    self.lbSetup.x = CGRectGetMaxX(filter.frame) + 2;
    self.lbSetup.centerY = view3.height/2;
    self.lbSetup.width = view3.width - self.lbSetup.x - 5;
    [view3 addSubview:self.lbSetup];
    
    UIView *line3 = [[UIView alloc]initWithFrame:CGRectMake(0, 49.5, kScreen_Width, 0.5)];
    line3.backgroundColor = CM_TABLE_BG_COLOR;
    [header addSubview:line3];
    [self.view addSubview:header];
}


- (void)filterSelection:(NSInteger)index {
    NSArray *data;
    NSString *title;
    if (index == 1) {
        title = @"产品系列";
        data = self.selectionData0;
    } else if (index == 2) {
        title = @"结构型式";
        data = self.selectionData1;
    } else if (index == 3) {
        title = @"安装型式";
        data = self.selectionData2;
    }
    
    if (data == nil || data.count == 0) {
        return;
    }
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil message: nil preferredStyle:UIAlertControllerStyleActionSheet];
    //修改title
    NSMutableAttributedString *alertControllerStr = [[NSMutableAttributedString alloc] initWithString:title];
    [alertControllerStr addAttribute:NSForegroundColorAttributeName value:BSBlackTextColor range:NSMakeRange(0, title.length)];
    [alertControllerStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18] range:NSMakeRange(0, title.length)];
    [alertController setValue:alertControllerStr forKey:@"attributedTitle"];
    
    for (NSDictionary *item in data) {
        [alertController addAction: [UIAlertAction actionWithTitle:[item objectForKey:@"name"] style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            if (index == 1) {
                self.lbSeries.text = [item objectForKey:@"name"];
            } else if (index == 2) {
                self.lbStruct.text = [item objectForKey:@"name"];
            } else {
                self.lbSetup.text = [item objectForKey:@"name"];
            }
            [self.tableView.mj_header beginRefreshing];
        }]];
    }
    [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
    [self presentViewController: alertController animated: YES completion: nil];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ProductListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"list"];
    NSDictionary *item = [self.dataSource objectAtIndex:indexPath.row];
    BOOL selected = NO;
    if (self.machineSelectedBlock != nil) {
        if (self.selectedGuids != nil && self.selectedGuids.count > 0) {
            for (NSString *guid in self.selectedGuids) {
                if ([guid isEqualToString:[item objectForKey:@"Id"]]) {
                    selected = YES;
                    break;
                } else {
                    selected = NO;
                }
            }
        }
    }
    cell.viewInfo = ^{
        ProductDetailViewController *vc = [ProductDetailViewController new];
        vc.product_type = @"fcu_equip";
        vc.equip_id = [item objectForKey:@"Id"];
        [self.navigationController pushViewController:vc animated:YES];
    };
    [cell setTitle:[item objectForKey:@"Model"] andSelectState:selected];
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *item = [self.dataSource objectAtIndex:indexPath.row];
    if (self.machineSelectedBlock != nil) {
        if (self.selectedGuids != nil && self.selectedGuids.count > 0) {
            BOOL find = NO;
            for (NSString *guid in self.selectedGuids) {
                if ([guid isEqualToString:[item objectForKey:@"Id"]]) {
                    find = YES;
                    [self.selectedGuids removeObject:guid];
                    break;
                }
            }
            if (!find) {
                [self.selectedGuids addObject:[item objectForKey:@"Id"]];
            }
        } else {
            self.selectedGuids = [NSMutableArray new];
            [self.selectedGuids addObject:[item objectForKey:@"Id"]];
        }
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    } else {
        ProductDetailViewController *vc = [ProductDetailViewController new];
        vc.product_type = @"fcu_equip";
        vc.equip_id = [item objectForKey:@"Id"];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, CGFLOAT_MIN)];
}

- (void)filterDataSource {
    NSString *sql = @"select * from FCU where 1=1 ";
    if (![self.lbSeries.text containsString:@"产品系列"]) {
        sql = [sql stringByAppendingString:[NSString stringWithFormat:@"and Series = '%@' ", self.lbSeries.text]];
    }
    if (![self.lbStruct.text containsString:@"结构型式"]) {
        sql = [sql stringByAppendingString:[NSString stringWithFormat:@"and StructType = '%@' ", self.lbStruct.text]];
    }
    if (![self.lbSetup.text containsString:@"安装型式"]) {
        sql = [sql stringByAppendingString:[NSString stringWithFormat:@"and InstallType = '%@' ", self.lbSetup.text]];
    }
    sql = [sql stringByAppendingString:@"order by Id"];
    [[DBManager manager]open:DB_FCU];
    self.dataSource = [[DBManager manager]queryArrayData:sql];
    [[DBManager manager]close];
    [self.tableView reloadData];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, CGFLOAT_MIN)];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
